<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button>get请求</button>
  <button>post请求--表单格式(窗体格式)</button>
  <button>post请求--JSON字符串</button>
  <script>
    document.querySelectorAll("button")[0].addEventListener("click", function () {
      //1 创建 XMLHttpRequest 对象
      let xhr = new XMLHttpRequest();

      //2 注册请求状态改变的回调函数
      xhr.onreadystatechange = function () {
        console.log(xhr.readyState);//请求状态0-4

        //5 判断请求状态为4
        if (xhr.readyState === 4) {
          //6 判断状态码
          if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
            console.log(xhr.status);
            console.log(xhr.statusText);
            console.log(xhr.responseText);
          }
        }
      }
      //3 打开链接
      xhr.open("GET", "http://192.168.0.85:3008/api/student/getStudent")

      // 4 发送请求
      xhr.send();
    })
    document.querySelectorAll("button")[1].addEventListener("click", function () {
      //1 创建 XMLHttpRequest 对象
      let xhr = new XMLHttpRequest();

      //2 注册请求状态改变的回调函数
      xhr.onreadystatechange = function () {
        console.log(xhr.readyState);//请求状态0-4

        //6 判断请求状态为4
        if (xhr.readyState === 4) {
          //7 判断状态码
          if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
            console.log(xhr.status);
            console.log(xhr.statusText);
            console.log(xhr.responseText);
          }
        }
      }
      //3 打开链接, 设置请求方式和url
      xhr.open("POST", "http://192.168.0.85:3008/api/student/addStudent");
      //4 设置请求数据为表单格式:
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

      //5 发送请求, 添加请求数据
      xhr.send("class=朱朵朵&age=18&gender=女&hobby=睡觉&address=郑州");
    })


    document.querySelectorAll("button")[2].addEventListener("click", function () {
      //1 创建 XMLHttpRequest 对象
      let xhr = new XMLHttpRequest();

      //2 注册请求状态改变的回调函数
      xhr.onreadystatechange = function () {
        console.log(xhr.readyState);//请求状态0-4

        //6 判断请求状态为4
        if (xhr.readyState === 4) {
          //7 判断状态码
          if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
            console.log(xhr.status);
            console.log(xhr.statusText);
            console.log(xhr.responseText);
          }
        }
      }
      //3 打开链接, 设置请求方式和url
      xhr.open("POST", "http://192.168.0.85:3008/api/student/addStudent");
      //4 设置请求数据为表单格式:
      xhr.setRequestHeader("Content-Type", "application/json");

      let data = {
        class: "田振齐",
        age: 18,
        gender: '女',
        hobby: '睡觉',
        address: '郑州'
      }
      //5 发送请求, 添加请求数据
      xhr.send(JSON.stringify(data));
    })



  </script>
</body>

</html>